package com.laoxu.java.thread;

/**
 * @Author laoxu
 * @Date 2022/11/23 14:55
 * @Desc 线程协作之管程法
 */
public class ThreadPipMethod {
    public static void main(String[] args) {
        SyncContainer container = new SyncContainer();
        Producer p = new Producer(container);
        Consumer c = new Consumer(container);
        p.start();
        c.start();
    }
}

// 生产者
class Producer extends Thread{
    SyncContainer container;

    public Producer(SyncContainer container){
        this.container = container;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            container.push(new Chicken(i));
            System.out.println("生产了第"+i+"只鸡");
        }
    }
}

// 消费者
class Consumer extends Thread{
    SyncContainer container;

    public Consumer(SyncContainer container){
        this.container = container;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("消费了第--->"+container.pop().id+"只鸡");
        }
    }
}

// 商品
class Chicken{
    int id;
    public Chicken(int id){
        this.id = id;
    }
}

// 缓冲区
class SyncContainer{
    // 容器
    Chicken[] chickens = new Chicken[10];
    // 容器计数器
    int count = 0;

    public synchronized void push(Chicken chicken){
        if(count == chickens.length){
            // 生产等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        chickens[count] = chicken;
        count++;
        // 通知消费者消费
        this.notifyAll();
    }

    public synchronized Chicken pop(){
        if(count ==0 ){
            // 等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        count--;
        Chicken chicken = chickens[count];
        // 消费完，通知生产者生产
        this.notifyAll();

        return chicken;
    }
}
